package com.hfb.mashibing.alip8.designpattern._10composite;

import java.util.LinkedList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;

public class Composite {

    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");

        Node c11 = new LeafNode("c11");
        Node c12 = new LeafNode("c12");
        BranchNode b21 = new BranchNode("section21");
        Node c211 = new LeafNode("c211");
        Node c212 = new LeafNode("c212");

        root.add(chapter1);
        root.add(chapter2);
        chapter1.add(c11);
        chapter1.add(c12);
        chapter2.add(b21);
        b21.add(c211);
        b21.add(c212);

        tree(root, 0);
    }
    static void tree(Node node, int depth){
//        if (depth != 0) System.out.print("└");
        if (depth != 0) System.out.print("|");
        for (int i = 0; i < depth; i++) {
            System.out.print("__");
        }
        node.p();
        if (node instanceof BranchNode) {
            for (Node n : ((BranchNode)node).nodes) {
                tree(n,depth+1);
            }
        }
    }
}
abstract class Node {
    abstract public void p();
}
@AllArgsConstructor
class LeafNode extends Node {
    String content;
    @Override
    public void p(){
        System.out.printf("%s\n", content);
    }
}
@Data
@AllArgsConstructor
class BranchNode extends Node {
    List<Node> nodes = new LinkedList<>();
    String name;
    public BranchNode(String name){this.name = name;}
    @Override
    public void p(){
        System.out.printf("%s\n", name);
    }
    public void add(Node n){
        nodes.add(n);
    }
}
